import os
import sys
import logging
from google.appengine.ext.webapp import template
from ftclient.authorization import oauth
from ftclient.ftclient import OAuthFTClient
from google.appengine.ext import webapp


class OAuthController(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), '../templates/oauth.html')
        self.response.out.write(template.render(path, {
                                                       'pagetitle' : 'Fusion Tables OAuth access request',
                                                       'title' : 'Fusion Tables OAuth access request'}))
    
    def post(self):
        consumerKey = self.request.get('consumerKey')
        consumerSecret = self.request.get('consumerSecret')
        domain = self.request.get('domain')
        
        #form the oauthready callback url
        hosturl = self.request.host_url
        callbackUrl = hosturl + '/oauthready'
        
        logging.info(consumerKey)
        logging.info(consumerSecret)
        logging.info(domain)
        logging.info(callbackUrl)
        
        #make the OAuth authorization request call
        auth_url, oauth_request_token,oauth_request_token_secret = oauth.OAuth().generateAuthorizationURL(
            consumer_key = consumerKey,
            consumer_secret = consumerSecret,
            domain = domain,
            callback_url = callbackUrl)
        
        #store the consumer key and secret entered in by the user in the session
        #store the token and secret for the above OAuth request made in the user session
        #all 4 pieces of the information stashed in the session are required to finally get the 
        #OAuth token and secret from the OAuth provider
        session = self.request.environ['beaker.session']
        session['consumerKey'] = consumerKey
        session['consumerSecret'] = consumerSecret
        session['oauth_request_token'] = oauth_request_token
        session['oauth_request_token_secret'] = oauth_request_token_secret
        #redirect the user to the authorization URL from the OAuth provider where the user will provide our application with the required access
        return self.redirect(auth_url)
    

class OAuthReadyController(webapp.RequestHandler):
    def get(self):
        session = self.request.environ['beaker.session']
        consumerKey = session.get('consumerKey')
        consumerSecret = session.get('consumerSecret')
        oauthRequestToken = session.get('oauth_request_token')
        oauthRequestTokenSecret = session.get('oauth_request_token_secret')
        
        logging.info(consumerKey)
        logging.info(consumerSecret)
        logging.info(oauthRequestToken)
        logging.info(oauthRequestTokenSecret)
        
        #make sure we have the four pieces of data required to get the OAuth token namely the
        #consumer key, consumer secret, oauth request token, oauth request token secret
        if(not(consumerKey and consumerSecret and oauthRequestToken and oauthRequestTokenSecret)):
            title = "Error requesting OAuth token and secret from Oauth provider"
            messages = list()
            if not consumerKey:
                messages.append('Consumer Key is missing in the current session.')
            if not consumerSecret:
                messages.append('Consumer Secret is missing in the current session.')
            if not oauthRequestToken:
                messages.append('The OAuth Request token is missing in the current session.')
            if not oauthRequestTokenSecret:
                messages.append('The OAuth Request token secret is missing in the current session.')
            self.render_error(title, messages)
            return
            
        access_token, access_secret = oauth.OAuth().authorize(
            consumer_key = consumerKey,
            consumer_secret = consumerSecret,
            oauth_token = oauthRequestToken,
            oauth_token_secret = oauthRequestTokenSecret)

        session['oauth_access_token'] = access_token
        session['oauth_access_token_secret'] = access_secret
        
        path = os.path.join(os.path.dirname(__file__), '../templates/oauthReady.html')
        self.response.out.write(template.render(path, {'oauth_token' : access_token,
                                                       'oauth_token_secret' : access_secret,
                                                       'pagetitle' : 'Fusion Tables OAuth access ready',
                                                       'title' : 'Fusion Tables OAuth access ready'}))
        
    def render_error(self, title, messages):
        path = os.path.join(os.path.dirname(__file__), '../templates/error.html')
        self.response.out.write(template.render(path, {'title' : title, 'messages' : messages}))
        

class FTManageController(webapp.RequestHandler):
    def oauthClient(self):
        session = self.request.environ['beaker.session']
        consumerKey = session.get('consumerKey')
        consumerSecret = session.get('consumerSecret')
        oauthToken = session.get('oauth_access_token')
        oauthTokenSecret = session.get('oauth_access_token_secret')
    
        client = OAuthFTClient(consumerKey, consumerSecret, oauthToken, oauthTokenSecret)
        return client

    def get(self):
        session = self.request.environ['beaker.session']
        consumerKey = session.get('consumerKey')
        consumerSecret = session.get('consumerSecret')
        oauthToken = session.get('oauth_access_token')
        oauthTokenSecret = session.get('oauth_access_token_secret')
        #make sure we have the four pieces of data required to get the OAuth token namely the
        #consumer key, consumer secret, oauth request token, oauth request token secret
        if(not(consumerKey and consumerSecret and oauthToken and oauthTokenSecret)):
            self.redirect('/oauth')
            
        path = os.path.join(os.path.dirname(__file__), '../templates/manageOAuth.html')
        self.response.out.write(template.render(path, {'results' : None, 'errors' : None,
                                                       'pagetitle' : 'Fusion Tables manager',
                                                       'title' : 'Fusion Tables manager'}))
        
    def post(self):
        session = self.request.environ['beaker.session']
        consumerKey = session.get('consumerKey')
        consumerSecret = session.get('consumerSecret')
        oauthToken = session.get('oauth_access_token')
        oauthTokenSecret = session.get('oauth_access_token_secret')
        #make sure we have the four pieces of data required to get the OAuth token namely the
        #consumer key, consumer secret, oauth request token, oauth request token secret
        if(not(consumerKey and consumerSecret and oauthToken and oauthTokenSecret)):
            self.redirect('/oauth')
        
        results = []
        errors = []
        query = self.request.get('query')
        if not query:
            errors = [('Query', 'Query is empty')]
        else:
            queries = query.splitlines()
            for qry in queries:
                response, content = self.oauthClient().query(qry)
                if(response.status != 200):
                    errors.append((qry, content))
                else:
                    results.append((qry, content))
        
        path = os.path.join(os.path.dirname(__file__), '../templates/manage.html')
        self.response.out.write(template.render(path, {'results' : results, 'errors' : errors}))

